import React, { useState, useEffect } from 'react';
import { Table, Input, Button, Tag, Space, message, Card, Row, Col } from 'antd';
import { SearchOutlined, StarOutlined, StarFilled } from '@ant-design/icons';

const CompanyList = () => {
  const [companies, setCompanies] = useState([]);
  const [favorites, setFavorites] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');

  // 模拟基金公司数据
  const mockCompanies = [
    {
      id: 1,
      name: '华夏基金管理有限公司',
      code: '000001',
      fundCount: 156,
      totalAssets: 8500,
      tags: ['大型基金公司', '股票型', '混合型'],
      rating: 5,
      description: '华夏基金成立于1998年，是中国首批成立的基金管理公司之一'
    },
    {
      id: 2,
      name: '易方达基金管理有限公司',
      code: '000002',
      fundCount: 189,
      totalAssets: 12000,
      tags: ['大型基金公司', '指数型', '债券型'],
      rating: 5,
      description: '易方达基金成立于2001年，是国内领先的综合性资产管理公司'
    },
    {
      id: 3,
      name: '嘉实基金管理有限公司',
      code: '000003',
      fundCount: 142,
      totalAssets: 6800,
      tags: ['大型基金公司', '成长型', '价值型'],
      rating: 4,
      description: '嘉实基金成立于1999年，专注于为投资者提供专业的资产管理服务'
    },
    {
      id: 4,
      name: '博时基金管理有限公司',
      code: '000004',
      fundCount: 98,
      totalAssets: 5200,
      tags: ['中型基金公司', '主题投资', '量化'],
      rating: 4,
      description: '博时基金成立于1998年，是国内首批成立的基金管理公司'
    },
    {
      id: 5,
      name: '南方基金管理有限公司',
      code: '000005',
      fundCount: 134,
      totalAssets: 7200,
      tags: ['大型基金公司', '稳健型', '固收+'],
      rating: 4,
      description: '南方基金成立于1998年，是中国证券投资基金行业的先行者'
    },
    {
      id: 6,
      name: '广发基金管理有限公司',
      code: '000006',
      fundCount: 167,
      totalAssets: 8900,
      tags: ['大型基金公司', '创新产品', 'FOF'],
      rating: 5,
      description: '广发基金成立于2003年，致力于为投资者创造长期稳定的投资回报'
    }
  ];

  useEffect(() => {
    setCompanies(mockCompanies);
    // 读取本地关注
    const stored = localStorage.getItem('companyFavorites');
    if (stored) setFavorites(JSON.parse(stored));
  }, []);

  const columns = [
    {
      title: '公司名称',
      dataIndex: 'name',
      key: 'name',
      width: 250,
      render: (name, record) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{name}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>代码: {record.code}</div>
        </div>
      ),
    },
    {
      title: '基金数量',
      dataIndex: 'fundCount',
      key: 'fundCount',
      width: 100,
      render: (count) => <span style={{ fontWeight: 'bold', color: '#1890ff' }}>{count}只</span>,
    },
    {
      title: '管理规模(亿)',
      dataIndex: 'totalAssets',
      key: 'totalAssets',
      width: 120,
      render: (assets) => <span style={{ fontWeight: 'bold', color: '#52c41a' }}>{assets}</span>,
    },
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      width: 200,
      render: (tags) => (
        <>
          {tags.map(tag => (
            <Tag color="blue" key={tag} style={{ marginBottom: '4px' }}>
              {tag}
            </Tag>
          ))}
        </>
      ),
    },
    {
      title: '评级',
      dataIndex: 'rating',
      key: 'rating',
      width: 100,
      render: (rating) => (
        <div>
          {[...Array(5)].map((_, index) => (
            <span key={index} style={{ color: index < rating ? '#faad14' : '#d9d9d9' }}>
              ★
            </span>
          ))}
        </div>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => {
        const isFavorited = favorites.some(fav => fav.id === record.id);
        return (
          <Button 
            type="link" 
            icon={isFavorited ? <StarFilled style={{ color: '#faad14' }} /> : <StarOutlined />}
            onClick={() => handleToggleFavorite(record)}
          >
            {isFavorited ? '已关注' : '关注'}
          </Button>
        );
      },
    },
  ];

  const handleToggleFavorite = (company) => {
    const isFavorited = favorites.some(fav => fav.id === company.id);
    let newFavorites;
    if (isFavorited) {
      newFavorites = favorites.filter(fav => fav.id !== company.id);
      message.success(`已取消关注 ${company.name}`);
    } else {
      newFavorites = [...favorites, company];
      message.success(`已关注 ${company.name}`);
    }
    setFavorites(newFavorites);
    localStorage.setItem('companyFavorites', JSON.stringify(newFavorites));
  };

  const handleRemoveFavorite = (companyId) => {
    const newFavorites = favorites.filter(fav => fav.id !== companyId);
    setFavorites(newFavorites);
    localStorage.setItem('companyFavorites', JSON.stringify(newFavorites));
    message.success('已从关注列表移除');
  };

  const handleSearch = (value) => {
    setSearchText(value);
  };

  const filteredData = companies.filter(company => 
    company.name.includes(searchText) || 
    company.tags.some(tag => tag.includes(searchText))
  );

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h2>基金公司管理</h2>
        <Input.Search
          placeholder="输入公司名称/标签"
          style={{ width: 400 }}
          onSearch={handleSearch}
          onChange={(e) => setSearchText(e.target.value)}
        />
      </div>

      <Row gutter={16}>
        <Col span={18}>
          <Table 
            dataSource={filteredData} 
            columns={columns} 
            rowKey="id"
            loading={loading}
            pagination={{
              total: filteredData.length,
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
            }}
          />
        </Col>
        <Col span={6}>
          <Card title="关注列表" style={{ position: 'sticky', top: '24px' }}>
            {favorites.length === 0 ? (
              <div style={{ textAlign: 'center', color: '#999', padding: '20px 0' }}>
                暂无关注的基金公司
              </div>
            ) : (
              <div>
                {favorites.map(company => (
                  <div 
                    key={company.id} 
                    style={{ 
                      padding: '12px', 
                      border: '1px solid #f0f0f0', 
                      borderRadius: '6px', 
                      marginBottom: '8px',
                      background: '#fafafa'
                    }}
                  >
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <div>
                        <div style={{ fontWeight: 'bold', fontSize: '14px' }}>{company.name}</div>
                        <div style={{ fontSize: '12px', color: '#666' }}>{company.fundCount}只基金</div>
                      </div>
                      <Button 
                        type="text" 
                        size="small" 
                        danger
                        onClick={() => handleRemoveFavorite(company.id)}
                      >
                        移除
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default CompanyList; 